package com.qf.util;

import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * IP归属地解析工具类（基于第三方API）
 * @USER: Administrator
 * @DATE: 2025/9/5 下午7:34
 * @VERSION: 1.0.0
 */
public class IpLocationUtils {
    /**
     * 解析IP归属地（示例使用免费API，生产环境建议使用稳定的付费服务）
     * 免费API可能有调用频率限制，需替换为可靠服务
     */
    public static String getLocationByIp(String ip) {
        if ("".equals(ip) || "127.0.0.1".equals(ip) || ip.startsWith("192.168.")) {
            return "本地网络";
        }

        // 示例API：实际项目中建议替换为阿里云、百度地图等稳定API
        String apiUrl = "https://api.ipify.org?format=json&ip=" + ip;

        try {
            URL url = new URL(apiUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);

            int responseCode = connection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
                in.close();

                // 解析API返回结果（不同API格式不同，需根据实际响应调整）
                JSONObject jsonObject = JSONObject.parseObject(response.toString());
                return jsonObject.getString("city") + " " + jsonObject.getString("region");
            }
        } catch (Exception e) {
            // 解析失败时不影响主流程，返回空
            e.printStackTrace();
        }
        return "";
    }
}
